<?php

namespace App\Service\OpenShop\Statistical;


use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\Common\ConfigModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Service\Common\CommonService;
use App\Service\Guanyuan\CurlService;
use Exception;
use Illuminate\Support\Facades\Log;

class SignOrderStatisticalService
{
    /**
     * @var int 开始时间
     */
    public int $startTime = 0;

    /**
     * @var int 结束时间
     */
    public int $endTime = 0;

    /**
     * @var array 省区信息
     */
    public array $areaList = [];

    /**
     * 获取每个省区的签约数 - 实时查询
     *
     * @return array
     */
    public function getSignOrderCount()
    {
        $signList = OpenShopUserExtContractModel::query()
                                                ->select(['id', 'contractId', 'signTime'])
                                                ->where('signTime', '>=', $this->startTime)
                                                ->with([
                                                    'userContractRel' => function ($query) {
                                                        $query->select(['orderNo', 'id']);
                                                    }
                                                ])
                                                ->get();
        // 总签约数
        $signOrderList = [];
        $signList->each(function ($item) use (&$signOrderList) {
            $signOrderList[] = $item->userContractRel->orderNo;
        });
        $signOrderList = array_unique($signOrderList);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()->whereIn('orderNo', $signOrderList)->get()->keyBy('orderNo');

        $allArea = $this->getInitAreaList(['newSignNum']);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {
                echo $order['orderNo'] . '省份不存在, 跳过.[新开门店数]' . PHP_EOL;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue']['newSignNum']++;
        }

        return $allArea;
    }

    /**
     * 获取新进选址门店 (开发待指派开始时间>=本周一)
     *
     * @param false $isTotal 是否查询所有
     * @param array $shopTag 查询门店标签
     * @return array
     */
    public function getNewWaitLocationCount()
    {
        $waitLocationList = OpenShopSiteMissionModel::query()
                                                    ->where('open_shop_site_mission.createdAt', '>=', $this->startTime)
//                                                    ->where('status', SiteMissionEnum::STATUS_1)
                                                    ->where('open_shop_site_mission.orderStatus',
                SignOrderEnum::ORDER_STATUS_OK)
                                                    ->whereIn('stepStatus', [
                                                        MissionTemplateEnum::STEP_STATUS_3
                                                    ])
                                                    ->rightJoin('open_shop_sign_order',
                                                        'open_shop_sign_order.orderNo',
                                                        '=',
                                                        'open_shop_site_mission.orderNo')
                                                    ->where('open_shop_sign_order.shopTag', '=', '')
                                                    ->select(['missionId', 'open_shop_site_mission.orderNo'])
                                                    ->get();

        $waitLocationTotal = [];
        $waitLocationList->each(function ($item) use (&$waitLocationTotal) {
            $waitLocationTotal[] = $item->orderNo;
        });
        $waitLocationTotal = array_unique($waitLocationTotal);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()
                                                 ->whereIn('orderNo', $waitLocationTotal)
                                                 ->get()
                                                 ->keyBy('orderNo');

        $key = 'newWaitLocationCount';

        $allArea = $this->getInitAreaList([$key]);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {
                echo $order['orderNo'] . $order['chooseShopAddressPrefix'] . '省份不存在, 跳过.[待选址数据]' . PHP_EOL;
                continue;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue'][$key]++;

//            if (in_array($order['chooseShopProvinceCode'], [110000, 120000, 130000])) {
//                dump($order->orderNo);
//            }

        }

        return $allArea;
    }

    /**
     * 获取每个省区的待选址数据 - 实时查询
     *
     * @param false $isTotal 是否查询所有
     * @param array $shopTag 查询门店标签
     * @return array
     */
    public function getWaitLocationCountV2(bool $isTotal = false, bool $isFirstShop = false)
    {
        $waitLocationList = OpenShopSiteMissionModel::query()
                                                    ->where('createdAt', '>=', $this->startTime)
//                                                    ->where('status', SiteMissionEnum::STATUS_1)
                                                    ->where('orderStatus', SignOrderEnum::ORDER_STATUS_OK)
                                                    ->whereIn('stepStatus', [
                                                        MissionTemplateEnum::STEP_STATUS_3
                                                    ])
                                                    ->select(['missionId', 'orderNo'])
                                                    ->get();


        $waitLocationTotal = [];
        $waitLocationList->each(function ($item) use (&$waitLocationTotal) {
            $waitLocationTotal[] = $item->orderNo;
        });
        $waitLocationTotal = array_unique($waitLocationTotal);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()
                                                 ->whereIn('orderNo', $waitLocationTotal)
                                                 ->get()
                                                 ->keyBy('orderNo');

        $key = 'waitLocationNum';
        $key .= ($isTotal === false ? '' : 'Total');
        $key .= ($isFirstShop === false ? '' : 'FirstShopTotal');

        $allArea = $this->getInitAreaList([$key]);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {
                echo $order['orderNo'] . $order['chooseShopAddressPrefix'] . '省份不存在, 跳过.[待选址数据]' . PHP_EOL;
                continue;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue'][$key]++;

//            if (in_array($order['chooseShopProvinceCode'], [110000, 120000, 130000])) {
//                dump($order->orderNo);
//            }
        }

        return $allArea;
    }

    /**
     * 获取每个省区的待选址数据 - 实时查询
     *
     * @param false $isTotal 是否查询所有
     * @param array $shopTag 查询门店标签
     * @return array
     */
    public function getWaitLocationCount(bool $isTotal = false, bool $isFirstShop = false)
    {
        // 获取选址中的门店信息 - 通过 OpenShopSiteMissionModel 可以获取历史数据 , 未支持标签查询
//        $waitLocationList = OpenShopSiteMissionModel::query()
//                                                    ->when(!$isTotal, function ($query) {
//                                                        $query->where('createdAt', '>=', $this->startTime);
//                                                    })
//                                                    ->where('status', SiteMissionEnum::STATUS_1)
//                                                    ->where('orderStatus', SignOrderEnum::ORDER_STATUS_OK)
//                                                    ->whereIn('stepStatus', [
//                                                        MissionTemplateEnum::STEP_STATUS_5,
//                                                        MissionTemplateEnum::STEP_STATUS_4,
//                                                        MissionTemplateEnum::STEP_STATUS_3
//                                                    ])
//                                                    ->select(['missionId', 'orderNo'])
//                                                    ->get();

        // 获取选址中的门店信息 2.0 - 通过 OpenShopMainProcessModel 获取实时数据
        $waitLocationList = OpenShopMainProcessModel::query()
                                                    ->join('open_shop_sign_order as order', 'order.mainProcessId', '=',
                                                        'open_shop_main_process.id')
                                                    ->where('order.status', SignOrderEnum::ORDER_STATUS_OK)
                                                    ->when(!$isTotal, function ($query) {
                                                        $query->where('open_shop_main_process.updatedAt', '>=',
                                                            $this->startTime);
                                                    })
                                                    ->when($isFirstShop, function ($query) {
                                                        // 查询首店订单 需满足 tag 为空 && tag 包含 首店的数据
                                                        $query->where(function ($query) {
                                                            $query->where('order.shopTag', '=', '');

                                                            $shopTag = ['首店'];
                                                            foreach ($shopTag as $tag) {
                                                                $query->orWhere('order.shopTag', 'like', "%{$tag}%");
                                                            }
                                                        });
                                                    })
                                                    ->whereIn('nowStepStatus', [
                                                        MissionTemplateEnum::STEP_STATUS_5,
                                                        MissionTemplateEnum::STEP_STATUS_4,
                                                        MissionTemplateEnum::STEP_STATUS_3
                                                    ])
                                                    ->get();

        $waitLocationTotal = [];
        $waitLocationList->each(function ($item) use (&$waitLocationTotal) {
            $waitLocationTotal[] = $item->orderNo;
        });
        $waitLocationTotal = array_unique($waitLocationTotal);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()
                                                 ->whereIn('orderNo', $waitLocationTotal)
                                                 ->get()
                                                 ->keyBy('orderNo');

        $key = 'waitLocationNum';
        $key .= ($isTotal === false ? '' : 'Total');
        $key .= ($isFirstShop === false ? '' : 'FirstShopTotal');

        $allArea = $this->getInitAreaList([$key]);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {
                echo $order['orderNo'] . $order['chooseShopAddressPrefix'] . '省份不存在, 跳过.[待选址数据]' . PHP_EOL;
                continue;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue'][$key]++;

//            if (in_array($order['chooseShopProvinceCode'], [110000, 120000, 130000])) {
//                dump($order->orderNo);
//            }
        }

        return $allArea;
    }

    /**
     * 获取每个省区的落址门店数据 - 实时查询
     *
     * @return array
     */
    public function getWaitMerchantsLocationCount()
    {
        // 等待本周落址门店
        $waitMerchantsLocationList = OpenShopSiteMissionModel::query()
                                                             ->where('open_shop_site_mission.completeAt', '>=',
                                                                 $this->startTime)
                                                             ->where('open_shop_site_mission.status',
                                                                 SiteMissionEnum::STATUS_2)
                                                             ->where('open_shop_site_mission.orderStatus',
                                                                 SignOrderEnum::ORDER_STATUS_OK)
                                                             ->where('open_shop_site_mission.stepStatus',
                                                                 MissionTemplateEnum::STEP_STATUS_5)
                                                             ->rightJoin('open_shop_sign_order',
                                                                 'open_shop_sign_order.orderNo',
                                                                 '=',
                                                                 'open_shop_site_mission.orderNo')
                                                             ->where('open_shop_sign_order.shopTag', '=', '')
                                                             ->select(['missionId', 'open_shop_site_mission.orderNo'])
                                                             ->get();
        $list                      = [];

        $waitMerchantsLocationList->each(function ($item) use (&$list) {
            $list[] = $item->orderNo;
        });
        $list = array_unique($list);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()->whereIn('orderNo', $list)->get()
                                                 ->keyBy('orderNo');

        $allArea = $this->getInitAreaList(['waitMerchantsLocationNum']);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {

                echo $order['orderNo'] . $order['chooseShopAddressPrefix'] . '不存在, 跳过.[落址门店数据]' . PHP_EOL;
                continue;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue']['waitMerchantsLocationNum']++;
//            dd($allArea);
//            if (in_array($order['chooseShopProvinceCode'], [320000, 370000, 430000, 450000, 460000])) {
//                dump($order->orderNo);
//            }
        }


        return $allArea;
    }

    /**
     * 获取每个省区的本周筹备中的店铺数据 - 实时查询
     * 本周新进筹备门店:家（建店信息待确认的开始时间 >= 本周一）
     *
     * @return array
     */
    public function getWaitPreparationsCount($isTotal = false)
    {
        // 筹备中门店
        $waitPreparationsList = OpenShopSiteMissionModel::query()
                                                        ->when(!$isTotal, function ($query) {
                                                            $query->where('createdAt', '>=', $this->startTime);
                                                        })
                                                        ->where('orderStatus', SignOrderEnum::ORDER_STATUS_OK)
                                                        ->where('status', SiteMissionEnum::STATUS_1)
                                                        ->when($isTotal, function ($query) {
                                                            $query->whereIn('stepStatus',
                                                                [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7]);
                                                        }, function ($query) {
                                                            $query->whereIn('stepStatus',
                                                                [17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7]);
                                                        })
                                                        ->select(['missionId', 'orderNo'])
                                                        ->get();
        $list                 = [];
        $waitPreparationsList->each(function ($item) use (&$list) {
            $list[] = $item->orderNo;
        });

        $list = array_unique($list);

        // 获取所有订单对应的省区数据
        $allOrderList = OpenShopUserBaseInfoModel::query()->whereIn('orderNo', $list)->get()
                                                 ->keyBy('orderNo');

        $key = 'waitPreparationsNum' . ($isTotal == false ? '' : 'Total');

        $allArea = $this->getInitAreaList([$key]);

        foreach ($allOrderList as $order) {
            // 异常处理
            if (empty($allArea[$order['chooseShopProvinceCode']])) {
                echo $order['orderNo'] . $order['chooseShopAddressPrefix'] . '省份不存在, 跳过.[筹备中门店]' . PHP_EOL;
                continue;
            }
            $allArea[$order['chooseShopProvinceCode']]['templateValue'][$key]++;
//            if (in_array($order['chooseShopProvinceCode'], [370000])) {
//                dump($order->orderNo);
//            }
        }

        return $allArea;
    }

    /**
     * 获取观远周表数据
     *
     * @return array
     */
    public function getGYStatusWeek(bool $isForceRefresh = false)
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh($isForceRefresh);
        $shopStatusWeek = $gwCurl->getFormatShopStatusWeek();

        $shopStatusWeek = $this->formatProvinceData($shopStatusWeek);
        $allArea        = $this->getInitAreaList([
            'newSignGWNumWeek',
            'newSignGWNumMonth',
            'newOpenShopNumWeek',
            'stillOpenShopNumWeek',
            'stillOpenShopNumMonth',
            'sumOpenShopNum',
            'suspendedOpenShopNumWeek',
            'suspendedOpenShopNumMonth',
            'closedShopNumYear',
            'newOpenShopNumMonthGyWeek', // 本月新开 - 周数据,
            'preparationsNumWeek', // 本周筹备
        ]);

        foreach ($shopStatusWeek as $shopStatus) {
            // 本周新签
            $allArea[$shopStatus['provinceCode']]['templateValue']['newSignGWNumWeek'] = $shopStatus['newSignGWNumWeek'];
            // 本周筹备
            $allArea[$shopStatus['provinceCode']]['templateValue']['preparationsNumWeek'] = $shopStatus['preparationsNumWeek'];
            // 本月新签
            $allArea[$shopStatus['provinceCode']]['templateValue']['newSignGWNumMonth'] = $shopStatus['newSignGWNumMonth'];
            // 本月新开
            $allArea[$shopStatus['provinceCode']]['templateValue']['newOpenShopNumMonthGyWeek'] = $shopStatus['newOpenShopNumMonthGyWeek'];
            // 本月在营门店数
            $allArea[$shopStatus['provinceCode']]['templateValue']['stillOpenShopNumMonth'] = $shopStatus['stillOpenShopNumMonth'];
            // 本年闭店
            $allArea[$shopStatus['provinceCode']]['templateValue']['closedShopNumYear'] = $shopStatus['closedShopNumYear'];
            // 本周新开门店数
            $allArea[$shopStatus['provinceCode']]['templateValue']['newOpenShopNumWeek'] = $shopStatus['newOpenShopNumWeek'];
            // 本周仍在营业数据
            $allArea[$shopStatus['provinceCode']]['templateValue']['stillOpenShopNumWeek'] = $shopStatus['stillOpenShopNumWeek'];
            // sumOpenShopNum
            $allArea[$shopStatus['provinceCode']]['templateValue']['sumOpenShopNum'] = $shopStatus['sumOpenShopNum'];
            // 本周暂停门店数 = 累计营门店数 - 本周在营门店数
            $allArea[$shopStatus['provinceCode']]['templateValue']['suspendedOpenShopNumWeek'] =
                $shopStatus['sumOpenShopNum'] - $shopStatus['stillOpenShopNumWeek'];
            // 本月暂停门店数 = 累计营门店数 - 本周在营门店数
            $allArea[$shopStatus['provinceCode']]['templateValue']['suspendedOpenShopNumMonth'] =
                $shopStatus['sumOpenShopNum'] - $shopStatus['stillOpenShopNumMonth'];
        }

        return $allArea;
    }

    public function getGyMonthSign()
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh(true);
        return $gwCurl->getMonthSign();
    }


    /**
     * 所有分公司列表
     *
     * @return array
     */
    public function getGyCompanyList()
    {
        $gwCurl = new CurlService();
        $result = $gwCurl->getCompanyList();
        return array_values(array_unique(array_column($result, 'area')));
    }


    /**
     * 获取观远年度总目标
     *
     * @param bool $isForceRefresh 是否强制刷新
     * @return array
     * @throws Exception
     */
    public function getGyAnnualShopData(bool $isForceRefresh = false)
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh($isForceRefresh);
        $annualShopData = $gwCurl->getFormatAnnualShopData();
        $annualShopData = $this->formatProvinceData($annualShopData);
        $allArea        = $this->getInitAreaList([
            'newOpenTargetNumMonth',
            'newOpenShopNumMonth',
            'newOpenShopNumYear',
            'gwStillOpenShopTargetNumYear',
            'closedShopNumLimitYear',
            'stillOpenShopNum',
        ]);

        foreach ($annualShopData as $shopStatus) {
            $allArea[$shopStatus['provinceCode']]['templateValue']['newOpenTargetNumMonth']        = $shopStatus['newOpenTargetNumMonth'];
            $allArea[$shopStatus['provinceCode']]['templateValue']['newOpenShopNumMonth']          = $shopStatus['newOpenShopNumMonth'];
            $allArea[$shopStatus['provinceCode']]['templateValue']['gwStillOpenShopTargetNumYear'] = $shopStatus['gwStillOpenShopTargetNumYear'];
            $allArea[$shopStatus['provinceCode']]['templateValue']['closedShopNumLimitYear']       = $shopStatus['closedShopNumLimitYear'];
            $allArea[$shopStatus['provinceCode']]['templateValue']['stillOpenShopNum']             = $shopStatus['stillOpenShopNum'];
            $allArea[$shopStatus['provinceCode']]['templateValue']['newOpenShopNumYear']           = $shopStatus['newOpenShopNumYear'];

            //            if (in_array($shopStatus['provinceCode'], [320000, 340000, 430000, 450000, 460000])) {
//                dump($shopStatus);
//            }
        }

        return $allArea;
    }

    /**
     * 获取观远签约机器人数据集
     *
     * @return array
     */
    public function getGyNewSignOrderRobotDataSource(string $date)
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh(true);
        $annualShopData = $gwCurl->getFormatOrderSignRobot($date);

        return $annualShopData;
    }

    /**
     * 格式化 公司数据输出
     *
     * @return array
     */
    public function formatCompanyDataSend(array $allArea)
    {
        // 组合成分公司的数据
        $companyData = [];

//        // 过滤 数字城市
//        $allArea = array_filter($allArea, function ($key) {
//            if (is_numeric($key)) {
//                return false;
//            }
//            return true;
//        }, ARRAY_FILTER_USE_KEY);

        foreach ($allArea as $area) {
            /**
             * 手动处理江苏的城市分类
             *
             * 江苏北：江苏、安徽
             * 江苏南：湖南、广西、海南
             */
//            if ($area['manageId'] == 2) {
//                if (in_array($area['provinceCode'], ['320000', '340000'])) {
//                    $area['name'] = '江苏分公司(苏北:江苏、安徽)';
//                } else {
//                    $area['name'] = '江苏分公司(苏南:湖南、广西、海南)';
//                }
//            }

            if (!key_exists($area['name'], $companyData)) {
                $companyData[$area['name']] = $area;
                continue;
            }

            foreach ($area['templateValue'] as $areaKey => $areaData) {
                $companyData[$area['name']]['templateValue'][$areaKey] += $areaData;
            }
        }

        $headOfficeManageId = 100;
        // 输出总部数据
        $headOfficeData = [];
        foreach ($companyData as $companyDatum) {
            if (!key_exists($headOfficeManageId, $headOfficeData)) {
                $headOfficeData[$headOfficeManageId]             = $companyDatum;
                $headOfficeData[$headOfficeManageId]['name']     = '总部';
                $headOfficeData[$headOfficeManageId]['manageId'] = $headOfficeManageId;
                continue;
            }
            foreach ($companyDatum['templateValue'] as $areaKey => $areaData) {
                $headOfficeData[$headOfficeManageId]['templateValue'][$areaKey] += $areaData;
            }
        }
        $companyData += $headOfficeData;

        // 默认海外组织机构 为 99

        return $companyData;
    }

    /**
     * 给观远的数据添加省区 code
     *
     * @param $allArea
     * @param $shopStatusWeek
     * @return mixed
     * @throws Exception
     */
    public function formatProvinceData($shopStatusWeek)
    {
        // 分公司以TIGER为主
        foreach ($shopStatusWeek as &$data) {
            startForeach:
            $allArea = array_column($this->getAllAreaList(), null, 'province');
            if (key_exists($data['province'], $allArea)) {
                $data['provinceCode'] = $allArea[$data['province']]['provinceCode'];
            } else {
                $this->addArea($data);
                goto startForeach;
            }
        }
        return $shopStatusWeek;
    }

    /**
     * 设置时间区间
     *
     * @param int $startTime
     * @param int $endTime
     */
    public function setTimeInterval(int $startTime, int $endTime)
    {
        $this->startTime = $startTime;
        $this->endTime   = $endTime;
    }

    /**
     * 获取初始化数据模板
     *
     * @param array $template
     * @return array
     */
    public function getInitAreaList(array $template = [])
    {
        $area = $this->getAllAreaList();

        foreach ($area as &$item) {
            foreach ($template as $value) {
                $item['templateValue'][$value] = 0;
            }
        }

        return $area;
    }

    /**
     * 添加不存在的省区
     */
    public function addArea(array $addArea)
    {
        $areaList       = $this->getAllAreaList();
        $areaTemp       = $this->getAreaTemp($addArea);
        $this->areaList = $areaList + $areaTemp;
    }

    /**
     * @return array
     */
    public function getAreaTemp($addArea)
    {
        $areaData = [
            "provinceCode" => $addArea['province'],
            "manageId"     => 13, // 表示 其余 都推给总部
            "province"     => $addArea['province']
        ];
        if ($addArea['area'] == '国外') {
            $areaData["name"] = '国外';
//            $areaData["manageId"] = 13;
        } else {
            $areaData["name"] = $addArea['province'] . '(Tiger 未划分省区, 请联系对应人员做出调整)';
//            $areaData["manageId"] = 13;
        }
        return [
            $addArea['province'] => $areaData
        ];
    }

    /**
     * 获取所有省区的信息
     *
     * @return array
     */
    public function getAllAreaList()
    {
        if (!$this->areaList) {
            // 获取所有省区
            $allOrg = OpenShopOrganizationManageModel::query()->with(['regionRel'])->get();

            // 处理反向数据
            $allArea = [];
            foreach ($allOrg as $org) {
                foreach ($org->regionRel as $reg) {
                    $allArea[$reg['provinceCode']] = [
                        'provinceCode' => $reg['provinceCode'],
                        'manageId'     => $reg['manageId'],
                        'province'     => $reg['provinceName'],
                        'name'         => $org->name,
                    ];
                }
            }

//            // 手动新增的省区
//            $manualArea = [
//                [
//                    'provinceCode' => 100,
//                    'manageId'     => 100,
//                    'provinceName' => '未划分省区',
//                    'name'         => '未划分省区',
//                ],
//                [
//                    'provinceCode' => 99,
//                    'manageId'     => 99,
//                    'provinceName' => '海外公司',
//                    'name'         => '海外公司'
//                ]
//            ];
//
//            foreach ($manualArea as $area) {
//                $allArea[$area['provinceCode']] = [
//                    'provinceCode' => $area['provinceCode'],
//                    'manageId'     => $area['manageId'],
//                    'province'     => $area['provinceName'],
//                    'name'         => $area['name'],
//                ];
//            }
            $this->areaList = $allArea;
        }

        return $this->areaList;
    }

    /**
     * 本年已过天数/本年总天数
     *
     * @return string
     */
    public static function getYTD()
    {
        $dayFirst = strtotime(date('Y-01-01'));
        $dayLast  = strtotime(date('Y-01-01', strtotime('+1 year')));
        $dayToday = strtotime(date('Y-m-d'));

        $diffDays      = ($dayLast - $dayFirst) / 86400;
        $diffTodayDays = ($dayToday - $dayFirst) / 86400;

        return bcdiv($diffTodayDays, $diffDays, 4) * 100;
    }

    public static function getMTD()
    {
        $dayFirst = strtotime(date('Y-m-01'));
        $dayLast  = strtotime(date('Y-m-01', strtotime('+1 month')));
        $dayToday = strtotime(date('Y-m-d'));

        $diffDays      = ($dayLast - $dayFirst) / 86400;
        $diffTodayDays = ($dayToday - $dayFirst) / 86400;

        return bcdiv($diffTodayDays, $diffDays, 4) * 100;
    }

    /**
     * 获取业绩分组数据
     *
     * @return mixed
     */
    public function getGYShangZengDaily()
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh(true);
        return $gwCurl->getShangZengDailyData();
    }

    public function getZhaoShangGroup()
    {
        $gwCurl = new CurlService();
        return $gwCurl->getZhaoShangGroup();
    }


    /**
     * 获取签约完成率
     *
     * @return mixed
     */
    public function getGYQianYuePercent()
    {
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh(true);
        return $gwCurl->getGYQianYuePercent();
    }

    /**
     * 获取优秀个人和团队数据
     * @param $startTime
     * @return array[]
     * @throws Exception
     */
    public static function getPersonalAndTeamData($startTime): array
    {
        //从观远获取
        $gwCurl = new CurlService();
        $gwCurl->setForceRefresh(true);
        $personal = $gwCurl->getFormatOrderSignPersonalRobot($startTime);
        $team     = $gwCurl->getFormatOrderSignTeamRobot($startTime);

        //排序 先根据金额 再根据总数
        if ($personal) {
            foreach ($personal as &$v) {
                $v['departmentName'] = str_replace('分公司', '', $v['departmentName']);
            }
            array_multisort(array_column($personal, 'reward'), SORT_DESC, array_column($personal, 'total'), SORT_DESC,
                $personal);
        }
        if ($team) {
            foreach ($team as &$v) {
                $v['departmentName'] = str_replace('分公司', '', $v['departmentName']);
            }
            array_multisort(array_column($team, 'reward'), SORT_DESC, array_column($team, 'total'), SORT_DESC, $team);
        }
        return [
            'personal' => $personal,
            'team'     => $team,
        ];
    }


    /**
     * 本月签约招商进度数据
     * @param $startTime
     * @return array[]
     * @throws Exception
     */
    public static function getMonthSigningCompletionData($startTime): array
    {
        // 从观远获取
        $gwCurl = new CurlService();

        $monthCompleteData = $gwCurl->getFormatMonthSigningCompletionRobot($startTime);
        $rankData          = $gwCurl->getFormatMonthSigningCompletionNoticeRobot($startTime);

        return [
            'monthCompleteData' => $monthCompleteData[0] ?? [],
            'rankData'          => $rankData ?? [],
        ];
    }


    /**
     * 本月省区机器人推送数据-全国
     * @param string $city 城市
     * @return array[]
     * @throws Exception
     */
    public static function getMonthProvincialData($city = ''): array
    {
        $siteTotal = $activeSiteTotal = $silentSiteTotal = $newSignShopTotal = $newSiteShopTotal = $monthDoNewTarget =
        $monthRealNewNumber = $monthDoNewNumber = $monthNewDiffNumber = $preTotalNumber = $preAbnormalNumber =
        $preNormalNumber = $monthPreNormalNumber = $monthPreNumber = $monthPreAbnormalNumber = $mallPermeateTotal =
        $sMallPermeateTotal = $aMallPermeateTotal = $dayGradeShopTotal = $jinniuGradeShopTotal = $problemGradeShopTotal =
        $normalGradeShopTotal = $starGradeShopTotal = $stGradeShopTotal = $dauShopTotal = $gmvTotal = $dayTotalAmount =
        $dayWaimaiTotalAmount = $lastMonthDormancyShopTotal = $directionalSiteTotal = $lossSiteTotal = $aMallPermeateTotalNumber =
        $sMallPermeateTotalNumber = $newSignTargetShopTotal = $wau = $mau = $au = $totalCanteenAmount = $clueNumTotal =
        $lastMonthMauShopTotal = 0;
        // 从观远获取
        $gwCurl = new CurlService();

        // 月度确址&新签门店数
        $markPenRateData = $gwCurl->getFormatMonthSiteNewShopRobotData();
        if ($markPenRateData) {
            foreach ($markPenRateData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                $newSignShopTotal       += (int)$v['newSignShop'];  //本月新签门店
                $newSiteShopTotal       += (int)$v['newSiteShop'];  //本月确址门店数
                $newSignTargetShopTotal += (int)$v['newSignTarget'];//本月签约目标
                $clueNumTotal           += (int)$v['clueNum'];      //本月线索量
            }
        }

        // 选址状态门店数
        $siteShopData = $gwCurl->getFormatSiteShopRobotData();
        if ($siteShopData) {
            foreach ($siteShopData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                $siteTotal += (int)$v['number'];
                switch ($v['status']) {
                    case "活跃客户":
                        $activeSiteTotal += (int)$v['number'];
                        break;
                    case "定向选址":
                        $directionalSiteTotal += (int)$v['number'];
                        break;
                    case "暂无计划":
                        $silentSiteTotal += (int)$v['number'];
                        break;
                    case "高风险流失":
                        $lossSiteTotal += (int)$v['number'];
                        break;
                }
            }
        }

        // 筹备&新开完成情况
        $preShopData = $gwCurl->getFormatPreparationsShopRobotData();
        if ($preShopData) {
            foreach ($preShopData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                $preTotalNumber         += (int)$v['preTotalNumber'];        //筹备中店数
                $preAbnormalNumber      += (int)$v['preAbnormalNumber'];     //筹备异常数
                $preNormalNumber        += (int)$v['preNormalNumber'];       //筹备正常数
                $monthPreNumber         += (int)$v['monthPreNumber'];        //当月待开
                $monthPreNormalNumber   += (int)$v['monthPreNormalNumber'];  //本月筹备正常
                $monthPreAbnormalNumber += (int)$v['monthPreAbnormalNumber'];//本月筹备异常
                $monthDoNewNumber       += (int)$v['monthDoNewNumber'];      //本月预计新开
                $monthDoNewTarget       += (int)$v['monthDoNewTarget'];      //新开目标数
                $monthRealNewNumber     += (int)$v['monthRealNewNumber'];    //实际新开数
                $monthNewDiffNumber     += (int)$v['monthNewDiffNumber'];    //本月差额数
            }
        }

        // 商场渗透率
        $markPenRateData = $gwCurl->getFormatMarkPenRateRobotData();
        if ($markPenRateData) {
            foreach ($markPenRateData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                switch ($v['grade']) {
                    case "A级":
                        $aMallPermeateTotal       += (int)$v['settledNumber'];
                        $aMallPermeateTotalNumber += (int)$v['number'];
                        break;
                    case "S级":
                        $sMallPermeateTotal       += (int)$v['settledNumber'];
                        $sMallPermeateTotalNumber += (int)$v['number'];
                        break;
                }
            }
        }

        // 日门店分级占比
        $dayShopGradeRobotData = $gwCurl->getFormatDayShopGradeRobotData();
        if ($dayShopGradeRobotData) {
            foreach ($dayShopGradeRobotData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                $dayGradeShopTotal += (int)$v['number'];
                switch ($v['grade']) {
                    case "金牛":
                        $jinniuGradeShopTotal += (int)$v['number'];
                        break;
                    case "问题":
                        $problemGradeShopTotal += (int)$v['number'];
                        break;
                    case "瘦狗":
                        $normalGradeShopTotal += (int)$v['number'];
                        break;
                    case "明星":
                        $starGradeShopTotal += (int)$v['number'];
                        break;
                    case "ST":
                        $stGradeShopTotal += (int)$v['number'];
                        break;
                }
            }
        }

        // 日DAU、实收数据
        $dayDauRealShopData = $gwCurl->getFormatDayDauRealShopRobotData();
        if ($dayDauRealShopData) {
            foreach ($dayDauRealShopData as $v) {
                if ($city && $v['city'] != 'NULL' && $city !== $v['city']) {
                    continue;
                }
                $dauShopTotal         += (int)$v['dau'];               //DAU门店数
                $gmvTotal             += (int)$v['gmv'];               //GMV
                $dayTotalAmount       += (int)$v['totalAmount'];       //实收金额
                $dayWaimaiTotalAmount += (int)$v['totalWaimaiAmount']; //外卖实收金额
                $wau                  += (int)$v['wau'];               //WAU
                $mau                  += (int)$v['mau'];               //MAU
                $au                   += (int)$v['au'];                //au
                $totalCanteenAmount   += (int)$v['totalCanteenAmount'];//堂食实收金额
            }
        }

        // 上月休眠门店数
        $monthDormancyShopData      = $gwCurl->getFormatMonthDormancyShopRobotData();
        $lastMonthDormancyShopTotal = array_sum(array_column($monthDormancyShopData, 'dormancyShopNum'));//上月休眠门店数
        $lastMonthMauShopTotal      = array_sum(array_column($monthDormancyShopData, 'mau'));            //上月MAU

        $monthDormancyKeyCityCount = 0; // 核心城市
        $monthDevelopCityCount     = 0; // 发展城市
        $monthNotDevelopCityCount  = 0; // 不发展城市
        if ($monthDormancyShopData) {
            foreach ($monthDormancyShopData as $v) {
                if ($v['cityType'] == '核心城市') {
                    $monthDormancyKeyCityCount += $v['dormancyShopNum'];
                } elseif ($v['cityType'] == '发展城市') {
                    $monthDevelopCityCount += $v['dormancyShopNum'];
                } else {
                    $monthNotDevelopCityCount += $v['dormancyShopNum'];
                }
            }
        }

        // 筹备异常明细门店数
        $unifiedOpenTotal     = $franchiseeReasonTotal = $noContractTotal = $otherReasonTotal = $notWithdrawnTotal =
        $unifiedOpenMonth = $franchiseeReasonMonth = $noContractMonth = $otherReasonMonth = $notWithdrawnMonth = 0;
        $monthPreAbnormalData = $gwCurl->getFormatMonthPreAbnormalRobotData();
        if ($monthPreAbnormalData) {
            foreach ($monthPreAbnormalData as $v) {
                $unifiedOpenCount = $franchiseeReasonCount = $noContractCount = $otherReasonCount = $notWithdrawnCount = 0;
                switch ($v['reason']) {
                    case "商场统一开业":
                    case "商场在建":
                        $unifiedOpenCount = 1;
                        break;
                    case "没有合同":
                        $noContractCount = 1;
                        break;
                    case "其它原因":
                    case "加盟商自身原因":
                    case "位置不满意":
                    case "位置风险":
                        $otherReasonCount = 1;
                        break;
                    case "上家未撤场":
                        $notWithdrawnCount = 1;
                        break;
                }
                $unifiedOpenTotal      += $unifiedOpenCount;
                $franchiseeReasonTotal += $franchiseeReasonCount;
                $noContractTotal       += $noContractCount;
                $otherReasonTotal      += $otherReasonCount;
                $notWithdrawnTotal     += $notWithdrawnCount;

                if (date('m') == date('m', strtotime($v['expectedOpeningTime']))) {// 当月
                    $unifiedOpenMonth      += $unifiedOpenCount;
                    $franchiseeReasonMonth += $franchiseeReasonCount;
                    $noContractMonth       += $noContractCount;
                    $otherReasonMonth      += $otherReasonCount;
                    $notWithdrawnMonth     += $notWithdrawnCount;
                }
            }
        }

        $totalData = [
            'newSignShopTotal'       => $newSignShopTotal,
            //本月新签数
            'newSiteShopTotal'       => $newSiteShopTotal,
            //本月确址数
            'newSignTargetShopTotal' => $newSignTargetShopTotal,
            //本月签约目标
            'newSignShopRate'        => self::bcdivtFormat($newSignShopTotal, $newSignTargetShopTotal),
            //本月新签数 完成率
            'clueNumTotal'           => $clueNumTotal,
            //本月线索量

            'monthDoNewTarget'   => $monthDoNewTarget,
            //新开目标数
            'monthRealNewNumber' => $monthRealNewNumber,
            //实际新开数
            'monthNewDiffNumber' => $monthNewDiffNumber,
            //本月差额数
            'monthRealNewRate'   => self::bcdivtFormat($monthRealNewNumber, $monthDoNewTarget),
            //新开完成率

            'siteTotal'            => $siteTotal,
            //选址中店数
            'activeSiteTotal'      => $activeSiteTotal,
            //活跃客户
            'directionalSiteTotal' => $directionalSiteTotal,
            //定向选址
            'silentSiteTotal'      => $silentSiteTotal,
            //暂无计划
            'lossSiteTotal'        => $lossSiteTotal,
            //高流失风险

            'sMallPermeateTotal' => $sMallPermeateTotal,
            //S级商场数
            'sMallPermeateRate'  => self::bcdivtFormat($sMallPermeateTotal, $sMallPermeateTotalNumber),
            //S级商场渗透率
            'aMallPermeateTotal' => $aMallPermeateTotal,
            //A级商场数
            'aMallPermeateRate'  => self::bcdivtFormat($aMallPermeateTotal, $aMallPermeateTotalNumber),
            //A级商场渗透率

            'preTotalNumber'         => $preTotalNumber,
            //筹备中店数
            'preNormalNumber'        => $preNormalNumber,
            //筹备正常数
            'preAbnormalNumber'      => $preAbnormalNumber,
            //筹备异常数
            'preAbnormalRate'        => self::bcdivtFormat($preAbnormalNumber, $preTotalNumber),
            //异常占比
            'monthPreNormalNumber'   => $monthPreNormalNumber,
            //本月筹备正常
            'monthPreAbnormalNumber' => $monthPreAbnormalNumber,
            //本月筹备异常
            'monthPreNumber'         => $monthPreNumber,
            //当月待开
            'monthDoNewNumber'       => $monthDoNewNumber,
            //本月预计新开
            'monthPreTotalNumber'    => $monthPreNormalNumber + $monthPreAbnormalNumber,
            //本月筹备总数

            'dauShopTotal'         => $dauShopTotal,
            //DAU门店数
            'gmvTotal'             => CommonService::floatNumber($gmvTotal),
            //GMV
            'wau'                  => $wau,
            //wau
            'mau'                  => $mau,
            //mau
            'au'                   => $au,
            //au
            'totalAmount'          => CommonService::floatNumber($dayTotalAmount),
            //实收金额
            'dayWaimaiTotalAmount' => CommonService::floatNumber($dayWaimaiTotalAmount),
            //外卖实收金额
            'totalCanteenAmount'   => CommonService::floatNumber($totalCanteenAmount),
            //堂食实收金额
            'waimaiRate'           => self::bcdivtFormat($dayWaimaiTotalAmount, $dayTotalAmount),
            //外卖占比
            'starShopRate'         => self::bcdivtFormat(($jinniuGradeShopTotal + $starGradeShopTotal),
                $dayGradeShopTotal),
            //明星、金牛店数、好店占比
            'normalShopRate'       => self::bcdivtFormat($normalGradeShopTotal, $dayGradeShopTotal),
            //瘦狗店数、占比
            'problemShopRate'      => self::bcdivtFormat($problemGradeShopTotal, $dayGradeShopTotal),
            //问题店数、占比
            'stShopRate'           => self::bcdivtFormat($stGradeShopTotal, $dayGradeShopTotal),
            //ST店数、占比

            'lastMonthDormancyShopTotal' => $lastMonthDormancyShopTotal,
            //上个自然月休眠门店数
            'dormancyShopRate'           => self::bcdivtFormat($lastMonthDormancyShopTotal, $lastMonthMauShopTotal),
            //休眠门店占比
            'dormancyShopRateKeyCity'           => self::bcdivtFormat($monthDormancyKeyCityCount, $lastMonthDormancyShopTotal),
            //核心城市休眠门店占比
            'dormancyShopRateOtherCity'           => self::bcdivtFormat($monthDevelopCityCount, $lastMonthDormancyShopTotal),
            //发展城市休眠门店占比
            'notDevelopShopRateOtherCity'           => self::bcdivtFormat($monthNotDevelopCityCount, $lastMonthDormancyShopTotal),
            //不发展城市休眠门店占比

            'unifiedOpenTotal'      => $unifiedOpenTotal,
            //商场统一开业原因门店数
            'franchiseeReasonTotal' => $franchiseeReasonTotal,
            //加盟商自身原因门店数
            'noContractTotal'       => $noContractTotal,
            //没有合同门店数
            'otherReasonTotal'      => $otherReasonTotal,
            //其它原因门店数
            'unifiedOpenMonth'      => $unifiedOpenMonth,
            //商场统一开业原因当月门店数
            'franchiseeReasonMonth' => $franchiseeReasonMonth,
            //加盟商自身原因当月门店数
            'noContractMonth'       => $noContractMonth,
            //没有合同当月门店数
            'otherReasonMonth'      => $otherReasonMonth,
            //其它原因当月门店数
            'notWithdrawnTotal'     => $notWithdrawnTotal,
            //上家未撤场门店数
            'notWithdrawnMonth'     => $notWithdrawnMonth,
            //上家未撤场当月门店数
        ];
        Log::info("debug_getMonthProvincialData：", $totalData);
        return [
            'totalData' => $totalData,
        ];
    }

    /**
     * @param int $num1
     * @param int $num2
     * @param int $scale
     * @return int|string
     */
    public static function bcdivtFormat(int $num1, int $num2, int $scale = 3)
    {
        if ($num1 == 0 || $num2 == 0) {
            return 0;
        }
        return bcdiv($num1, $num2, $scale) * 100 . "%";
    }


    /**
     * 本月省区机器人推送数据-分公司
     * @return array[]
     * @throws Exception
     */
    public static function getMonthBranchData(): array
    {
        $newSignData = $newRealNewData = [];
        // 从观远获取
        $gwCurl = new CurlService();

        // 月度确址&新签门店数
        $markPenRateData = $gwCurl->getFormatMonthSiteNewShopRobotData();
        if ($markPenRateData) {
            foreach ($markPenRateData as $v) {
                if (!$v['branch']) {
                    continue;
                }
                if (!isset($newSignData[$v['branch']])) {
                    $newSignData[$v['branch']]['newSignShop'] = (int)$v['newSignShop'];  //本月新签门店
                    $newSignData[$v['branch']]['branch']      = str_replace('分公司', '', $v['branch']);//分公司
                    continue;
                }
                $newSignData[$v['branch']]['newSignShop'] += (int)$v['newSignShop'];  //本月新签门店
            }
            $newSignData = array_values($newSignData);
            array_multisort(array_column($newSignData, 'newSignShop'), SORT_DESC, $newSignData);
        }

        // 筹备&新开完成情况
        $preShopData = $gwCurl->getFormatPreparationsShopRobotData();
        if ($preShopData) {
            foreach ($preShopData as $v) {
                if (!$v['branch']) {
                    continue;
                }
                if (!isset($newRealNewData[$v['branch']])) {
                    $newRealNewData[$v['branch']]['monthDoNewTarget']   = (int)$v['monthDoNewTarget'];      //新开目标数
                    $newRealNewData[$v['branch']]['monthRealNewNumber'] = (int)$v['monthRealNewNumber'];    //实际新开数
                    $newRealNewData[$v['branch']]['branch']             = str_replace('分公司', '', $v['branch']);//分公司
                    continue;
                }
                $newRealNewData[$v['branch']]['monthDoNewTarget']   += (int)$v['monthDoNewTarget'];      //新开目标数
                $newRealNewData[$v['branch']]['monthRealNewNumber'] += (int)$v['monthRealNewNumber'];    //实际新开数
            }
            $newRealNewData = array_values($newRealNewData);
            foreach ($newRealNewData as &$v) {
                $v['monthRealNewRate'] = self::bcdivtFormat($v['monthRealNewNumber'], $v['monthDoNewTarget'], 2);
            }
            array_multisort(
                array_column($newRealNewData, 'monthRealNewNumber'), SORT_DESC,
                array_column($newRealNewData, 'monthRealNewRate'), SORT_DESC, $newRealNewData
            );
        }

        return [
            'newSignData'    => $newSignData,
            'newRealNewData' => $newRealNewData,
        ];
    }


    /**
     * 当月开发确址排行榜
     * @return array[]
     * @throws Exception
     */
    public static function getMonthDevelopRankData(): array
    {
        $data = [];
        // 从观远获取
        $gwCurl = new CurlService();

        // 开发当月任务数
        $developRankData = $gwCurl->getFormatMonthDevelopRankRobotData();
        if ($developRankData) {
            foreach ($developRankData as $v) {
                if (!$v['branch'] || !$v['nickname']) {
                    continue;
                }
                if (!isset($data[$v['branch']][$v['nickname']])) {
                    $data[$v['branch']][$v['nickname']]['taskNum']  = (int)$v['taskNum'];         //当月任务数
                    $data[$v['branch']][$v['nickname']]['siteShop'] = (int)$v['siteShop'];        //本月确址门店
                    $data[$v['branch']][$v['nickname']]['nickname'] = $v['nickname'];             //开发经理昵称
                    $data[$v['branch']][$v['nickname']]['branch']   = $v['branch'];               //区域
                }
            }

            foreach ($data as &$v) {
                foreach ($v as &$vv) {
                    $vv['rate'] = self::bcdivtFormat($vv['siteShop'], $vv['taskNum'], 2);
                }
                array_multisort(
                    array_column($v, 'siteShop'), SORT_DESC,
                    array_column($v, 'rate'), SORT_DESC,
                    array_column($v, 'taskNum'), SORT_DESC, $v
                );
            }
        }


        return [
            'totalData' => $data,
        ];
    }

    /**
     * 生炸鸡腿数据
     * @param string $date
     * @return array[]
     * @throws Exception
     */
    public static function getFriedChickenLegData(string $date): array
    {
        $data = $shopData = [];
        // 从观远获取
        $gwCurl = new CurlService();

        // 生炸鸡腿数据
        $friedChickenLegData = $gwCurl->getFriedChickenLegRobotData($date);

        if ($friedChickenLegData) {

            $dayDauRealShopData = $gwCurl->getFormatDayDauRealShopRobotData();
            $totalMau           = 0;// 全国在营门店数
            if ($dayDauRealShopData) {
                $totalMau = array_sum(array_column($dayDauRealShopData, 'mau')); //MAU
            }

            $total = [
                'orderGoodsDayNum'     => 0,
                'orderStoreDayNum'     => 0,
                'actualIncome'         => 0,
                'takeawayActualIncome' => 0,
                'gmv'                  => 0,
                'takeawayGmv'          => 0,
                'salesVolume'          => 0,
                'takeawaySalesVolume'  => 0,
                'province'             => '全国',
                'date'                 => $date,
                'orderGoodsTotalNum'   => 0,
                'orderStoreTotalNum'   => 0,
                'shopNum'              => $totalMau,
            ];
            foreach ($friedChickenLegData as $v) {
                $total['orderGoodsDayNum']     += $v['orderGoodsDayNum'] ?? 0;
                $total['orderStoreDayNum']     += $v['orderStoreDayNum'] ?? 0;
                $total['actualIncome']         += $v['actualIncome'] ?? 0;
                $total['takeawayActualIncome'] += $v['takeawayActualIncome'] ?? 0;
                $total['gmv']                  += $v['gmv'] ?? 0;
                $total['takeawayGmv']          += $v['takeawayGmv'] ?? 0;
                $total['salesVolume']          += $v['salesVolume'] ?? 0;
                $total['takeawaySalesVolume']  += $v['takeawaySalesVolume'] ?? 0;
                $total['orderGoodsTotalNum']   += $v['orderGoodsTotalNum'] ?? 0;
                $total['orderStoreTotalNum']   += $v['orderStoreTotalNum'] ?? 0;
            }

            $friedChickenLegData = array_merge([$total], $friedChickenLegData);

            foreach ($friedChickenLegData as $v) {
                $shopPenetrationRate = $v['shopPenetrationRate'] ?? 0;
                if (!$shopPenetrationRate) {
                    $shopPenetrationRate = self::bcdivtFormat($v['orderStoreTotalNum'], $v['shopNum'], 2);
                } else {
                    $shopPenetrationRate = round($shopPenetrationRate * 100) . '%';
                }
                $data[]     = [
                    'province'            => $v['province'],                        // 省
                    'shopNum'             => (int)$v['shopNum'],                    // 本月在营
                    'orderStoreTotalNum'  => (int)$v['orderStoreTotalNum'],         // 累计订货门店数
                    'orderGoodsTotalNum'  => (int)$v['orderGoodsTotalNum'],         // 累计订货箱数
                    'shopPenetrationRate' => $shopPenetrationRate,                  // 渗透率 sum(累计订货门店数)/sum(本月在营)
                    'orderStoreDayNum'    => (int)$v['orderStoreDayNum'],           // 当天订货门店数
                    'orderGoodsDayNum'    => (int)$v['orderGoodsDayNum'],           // 当天订货箱数
                ];
                if ($v['province'] == '全国') {
                    $shopData[] = [
                        'province'             => $v['province'],                                    // 省
                        'actualIncome'         => round($v['actualIncome'] / 1000, 1),          // 堂食实收
                        'salesVolume'          => round($v['salesVolume'] / 1000, 1),           // 堂食销量
                        'takeawayActualIncome' => round($v['takeawayActualIncome'] / 1000, 1), // 外卖实收
                        'takeawaySalesVolume'  => round($v['takeawaySalesVolume'] / 1000, 1), // 外卖销量
                        'takeawayRate'         => self::bcdivtFormat(
                            $v['takeawayActualIncome'],
                            ($v['actualIncome'] + $v['takeawayActualIncome']), 2
                        ),// 外卖占比 外卖实收/(堂食实收+外卖实收)
                    ];
                }
            }
        }
        if ($data) {
            array_multisort(
                array_column($data, 'shopNum'), SORT_DESC,
                array_column($data, 'orderStoreTotalNum'), SORT_DESC,
                $data
            );
        }
        if ($shopData) {
            array_multisort(
                array_column($shopData, 'actualIncome'), SORT_DESC,
                array_column($shopData, 'takeawayActualIncome'), SORT_DESC,
                $shopData
            );
        }

        return [
            'totalData' => $data,
            'shopData'  => $shopData,
        ];
    }

}
